/*
 * Copyright (c) 2020 - ~, HIT_HERO Team
 *
 * PULSE ENCODER MODULE SOUCE FILE
 * Used in RT-Thread Operate System
 *
 * Change Logs:
 * Date           Author       Notes                Mail
 * 2020-09-03     WangXi       first version        WangXi_chn@foxmail.com
 */
 
#include "Module_PulseEncoder.h"

static void     Module_PulseEncoderInit(MODULE_PULSEENCODER *module);
static void     Module_PulseEncoderRead(MODULE_PULSEENCODER *module);
static void     Module_PulseEncoderClear(MODULE_PULSEENCODER *module);

/* Global Method */
rt_err_t Module_PulseEncoder_Config(MODULE_PULSEENCODER *module)
{
    if( module->Method_Init     ==NULL &&
        module->Method_Read		==NULL &&
		module->Method_Clear	==NULL
                
    ){  
        /* Link the Method */
        module->Method_Init         = Module_PulseEncoderInit;
        module->Method_Read			= Module_PulseEncoderRead;
		module->Method_Clear		= Module_PulseEncoderClear;
        
    }
    else{
        rt_kprintf("Warning: Module BspCommunicate is Configed twice\n");
        return RT_ERROR;
    }

    /* Device Init */
    module->Method_Init(module);

    return RT_EOK;
}

static void Module_PulseEncoderInit(MODULE_PULSEENCODER *module)
{
	rt_err_t ret = RT_EOK;

	/* find pulse encode device */
    module->Value_pulse_dev = rt_device_find(module->Property_PulseDevName);
    if (module->Value_pulse_dev == RT_NULL)
    {
        rt_kprintf("pulse encoder sample run failed! can't find %s device!\n", module->Property_PulseDevName);
        return;
    }

    /* open the device in readonly mode */
    ret = rt_device_open(module->Value_pulse_dev, RT_DEVICE_OFLAG_RDONLY);
    if (ret != RT_EOK)
    {
        rt_kprintf("open %s device failed!\n", module->Property_PulseDevName);
        return;
    }
	
	rt_pin_mode(module->Property_CH1_pin, PIN_MODE_INPUT_PULLUP);
	rt_pin_mode(module->Property_CH2_pin, PIN_MODE_INPUT_PULLUP);
}

static void Module_PulseEncoderRead(MODULE_PULSEENCODER *module)
{
	rt_device_read(module->Value_pulse_dev, 0, &(module->Value_pulseNum), 1);		
}

static void Module_PulseEncoderClear(MODULE_PULSEENCODER *module)
{
	
	rt_device_control(module->Value_pulse_dev, PULSE_ENCODER_CMD_CLEAR_COUNT, RT_NULL);
	module->Value_pulseNum = 0;
}





/************************ (C) COPYRIGHT 2020 WANGXI **************END OF FILE****/
